package com.leave.dao;

import com.leave.entity.Admin;
import com.leave.entity.Classes;
import org.apache.commons.lang3.StringUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * sys_user 管理员
 * id 管理员账号
 */
public class AdminDao {
    private JdbcTemplate jdbcTemplate;
    public List<Admin> query(Admin admin){
        String sql ="select * from sys_user where 1=1 ";
        List<Object> paramValues=new ArrayList<>();
        List<Admin> adminList=new ArrayList<>();
        if(admin!=null){
            if(admin.getUserid()!=null&&!"".equals(StringUtils.trim(admin.getUserid()))){
                sql+=" and userid=?";
                paramValues.add(admin.getUserid());
            }
            if(admin.getPassword()!=null&&!"".equals(StringUtils.trim(admin.getPassword()))){
                sql+=" and password=?";
                paramValues.add(admin.getPassword());
            }
        }
//        System.out.println(sql);
        adminList =jdbcTemplate.query(sql, paramValues.toArray(), new RowMapper<Admin>() {
            @Override
            public Admin mapRow(ResultSet rs, int rowNum) throws SQLException {
//                System.out.println(123);
               Admin admin1=new Admin();
                String userid =rs.getString("userid");
                String fullname =rs.getString("fullname");
                String password =rs.getString("password");
                String tel =rs.getString("telephone");
                admin1.setPassword(password);
                admin1.setFullname(fullname);
                admin1.setUserid(userid);
                admin1.setTelephone(tel);
//                System.out.println(admin1);
                return admin1;
            }
        });
//        System.out.println(adminList);
        return adminList;
    }

    public void update(Admin admin) {
        // 声明更新 SQL 字符串变量 sql
        String sql = "update sys_user set userid=?, fullname=?, password=?, telephone=? where userid=?";
        if (admin != null) {
            String[] paramValues = {admin.getUserid(), admin.getFullname(), admin.getPassword(), admin.getTelephone(), admin.getUserid()};
            jdbcTemplate.update(sql, paramValues);
        }
    }

    /**
     *  setter注入方式，注意不需要定义getter方法。
     * @param jdbcTemplate
     */
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
}
